package com.yexx.idempotent.web;

import com.yexx.starter.optms.idempotent.annotation.Idempotent;
import com.yexx.starter.optms.idempotent.template.LockTemplate;
import com.yexx.starter.optms.logger.common.TraceConstants;
import com.yexx.starter.optms.logger.contexts.GlobalContextHolder;
import com.yexx.starter.uid.common.UidGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * description:测试
 *
 * @author: zuomin (myleszelic@outlook.com)
 * @date 2022/06/02:08:33
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class DemoController {

    @GetMapping("/demo")
    @Idempotent(expiredTime = 10, unlockKey = true)
    public String demo(){
        log.info("test demo success userId : [{}] traceId : [{}], tenantId : [{}]", GlobalContextHolder.getContext(TraceConstants.USER_ID), GlobalContextHolder.getContext(TraceConstants.TRACE_ID), GlobalContextHolder.getContext(TraceConstants.TENANT_ID));
        return "success";
    }

    @Resource
    private LockTemplate lockTemplate;

    @GetMapping("/lock")
    public String lock(String param) throws InterruptedException {
        lockTemplate.lock("test");
        try {
            log.info("[{}]", param);
            TimeUnit.SECONDS.sleep(5L);
        } finally {
            lockTemplate.unLock("test");
        }

        return "success";
    }

    @Resource
    private UidGenerator uidGenerator;

    @GetMapping("/uid")
    @Idempotent(expiredTime = 10, unlockKey = true)
    public String uid(){
        log.info("uid : [{}]", uidGenerator.generate());
        return "success";
    }

}
